import 'package:flutter/material.dart';
import '../models/book.dart';
import '../services/chapter_service.dart';
import '../services/epub_service.dart';
import 'package:flutter/foundation.dart' show kIsWeb, compute;
import 'dart:convert';

class BookDetailPage extends StatefulWidget {
  final Book book;
  const BookDetailPage({super.key, required this.book});

  @override
  State<BookDetailPage> createState() => _BookDetailPageState();
}

class _BookDetailPageState extends State<BookDetailPage> {
  List<ChapterInfo> _chapterInfos = [];
  String? _fullContent;
  final Map<int, String> _chapterContentCache = {};
  int _selectedChapter = 0;
  bool _loading = true;
  String? _error;
  List<EpubChapter> _epubChapters = [];
  int _selectedEpubChapter = 0;
  bool _isEpub = false;

  @override
  void initState() {
    super.initState();
    _loadContent();
  }

  Future<void> _loadContent() async {
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      if (widget.book.type == 'epub') {
        final chapters =
            (await parseEpubChapters(widget.book)).cast<EpubChapter>();
        if (chapters.isEmpty) {
          setState(() {
            _error = '未找到章节';
            _loading = false;
          });
        } else {
          setState(() {
            _epubChapters = chapters;
            _isEpub = true;
            _loading = false;
          });
        }
      } else {
        String content = await _readBookContent(widget.book);
        List<ChapterInfo> chapterInfos;
        if (kIsWeb) {
          chapterInfos = splitChaptersInfo(content);
        } else {
          chapterInfos = await compute(splitChaptersInfo, content);
        }
        setState(() {
          _fullContent = content;
          _chapterInfos = chapterInfos;
          _loading = false;
        });
        _loadChapterContent(0);
      }
    } catch (e) {
      setState(() {
        _error = e.toString();
        _loading = false;
      });
    }
  }

  Future<String> _readBookContent(Book book) async {
    if (book.contentBase64 != null) {
      return String.fromCharCodes(
        const Base64Decoder().convert(book.contentBase64!),
      );
    } else if (book.path != null) {
      try {
        final file = await Future.value(book.path!);
        return await Future.value(file);
      } catch (e) {
        return '读取失败：$e';
      }
    } else {
      return '无内容';
    }
  }

  Future<void> _loadChapterContent(int idx) async {
    if (_chapterContentCache.containsKey(idx) || _fullContent == null) return;
    final info = _chapterInfos[idx];
    final body = getChapterContent(_fullContent!, info);
    setState(() {
      _chapterContentCache[idx] = body;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.book.name)),
      body:
          _loading
              ? const Center(child: CircularProgressIndicator())
              : _error != null
              ? Center(child: Text('加载失败: $_error'))
              : _isEpub
              ? Row(
                children: [
                  // 目录
                  Container(
                    width: 120,
                    color: Colors.grey[200],
                    child: ListView.builder(
                      itemCount: _epubChapters.length,
                      itemBuilder:
                          (context, idx) => ListTile(
                            title: Text(
                              _epubChapters[idx].title,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: const TextStyle(fontSize: 13),
                            ),
                            selected: idx == _selectedEpubChapter,
                            onTap: () {
                              setState(() {
                                _selectedEpubChapter = idx;
                              });
                            },
                          ),
                    ),
                  ),
                  // 内容
                  Expanded(
                    child: Padding(
                      padding: const EdgeInsets.all(16.0),
                      child:
                          _epubChapters[_selectedEpubChapter].textContent !=
                                  null
                              ? SingleChildScrollView(
                                child: Text(
                                  _epubChapters[_selectedEpubChapter]
                                      .textContent!,
                                  style: const TextStyle(fontSize: 16),
                                ),
                              )
                              : PageView.builder(
                                itemCount:
                                    _epubChapters[_selectedEpubChapter]
                                        .images
                                        ?.length ??
                                    0,
                                itemBuilder: (context, idx) {
                                  final img =
                                      _epubChapters[_selectedEpubChapter]
                                          .images![idx];
                                  return Center(
                                    child: Image.memory(
                                      img,
                                      fit: BoxFit.contain,
                                    ),
                                  );
                                },
                              ),
                    ),
                  ),
                ],
              )
              : Row(
                children: [
                  // 目录
                  Container(
                    width: 120,
                    color: Colors.grey[200],
                    child: ListView.builder(
                      itemCount: _chapterInfos.length,
                      itemBuilder:
                          (context, idx) => ListTile(
                            title: Text(
                              _chapterInfos[idx].title,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: const TextStyle(fontSize: 13),
                            ),
                            selected: idx == _selectedChapter,
                            onTap: () async {
                              setState(() {
                                _selectedChapter = idx;
                              });
                              await _loadChapterContent(idx);
                            },
                          ),
                    ),
                  ),
                  // 内容
                  Expanded(
                    child: Padding(
                      padding: const EdgeInsets.all(16.0),
                      child:
                          _chapterContentCache[_selectedChapter] == null
                              ? const Center(child: CircularProgressIndicator())
                              : SingleChildScrollView(
                                child: Text(
                                  _chapterContentCache[_selectedChapter]!
                                          .isEmpty
                                      ? '（本章节无内容）'
                                      : _chapterContentCache[_selectedChapter]!,
                                  style: const TextStyle(fontSize: 16),
                                ),
                              ),
                    ),
                  ),
                ],
              ),
    );
  }
}
